<template>
  <div class="app-container experiment_data">
    <div class="left_container common_shadow">
      <template v-if="experimentList.length > 0">
        <div v-for="(item, index) in experimentList"
           :class="'experiment_item' + (index === activeIndex ? ' experiment_item__active' : '')"
           @click="handleExperimentChange(index)">
        <div class="active_block" v-show="index === activeIndex"></div>
        <div class="experiment_info">
          <span>{{item.schemeName}}</span>
          <span>{{item.schemeProducer}}</span>
        </div>
        <div class="experiment_time">
          {{new Date(item.startTime).toLocaleDateString()}} ~ {{new Date(item.endTime).toLocaleDateString()}}
        </div>
        <i class="el-icon-arrow-right active_arrow" v-show="index === activeIndex"></i>
      </div>
      </template>
      <el-empty v-else style="margin-top: 30px" description="暂无数据"></el-empty>
      <pagination
        class="pagination_container"
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <div :class="charts.length === 0 ? 'right_container white_bg common_shadow' : 'right_container'" v-loading="dataLoading">
      <template v-if="charts.length > 0">
        <div class="right_item white_bg common_shadow" v-for="(item, index) in charts">
          <div class="chart_title_container">
            <div>
              <div class="prev_block"></div>
              <div class="chart_title">{{item.name}}--历史数据记录</div>
            </div>
            <el-button style="margin: 0 10px;" type="text" @click="exportData(item)">导出</el-button>
          </div>
          <template v-if="item.type === '0'">
            <span style="font-size: 14px; color: #777;position: absolute; top: 44px;left: 16px">方差： {{item.fc}}</span>
            <ECharts ref="weiYi" class="charts_container" :options="item.options"></ECharts>
          </template>
          <template v-else-if="item.type === '1'">
            <video-player  class="video-player charts_container vjs-custom-skin"
                           ref="videoPlayer"
                           :playsinline="true"
                           :options="item.playerOptions"
            ></video-player>
          </template>
          <template v-else-if="item.type === '2'">
            <ECharts ref="station" class="charts_container" :options="item.options"></ECharts>
          </template>
        </div>
      </template>
      <el-empty v-else style="margin-top: 30px" description="暂无数据"></el-empty>
    </div>
  </div>
</template>

<script>
import { debounce, commonGrid, calcFc} from "../../../utils";
import { listScheme, getScheme, delScheme, addScheme, updateScheme, exportScheme } from "@/api/business/scheme";
import { getSchemeData } from "../../../api/business/scheme";
import { exportCollected_data } from "@/api/business/collected_data";


export default {
  name: "index",
  data() {
    return {
      experimentList: [],
      activeIndex: 0,
      charts: [],
      dataLoading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 8,
        schemeId: null,
        schemeName: null,
        operator: null,
        operateTime: null,
        templateId: null,
        templateName: null
      },
      total: 0
    }
  },
  methods: {
    /** 查询实验方案列表 */
    getList() {
      this.loading = true;
      this.experimentList = [];
      listScheme(this.queryParams).then(response => {
        this.experimentList = response.rows;
        this.total = response.total;
        this.loading = false;
        if (response.rows.length > 0) {
          this.currentSchemeId = response.rows[0].schemeId;
          this.dataLoading = true;
          this.charts = [];
          getSchemeData({schemeId: response.rows[0].schemeId, size: 100}).then(res => {
            res.data.forEach(item => {
              if (item.type === '0') {
                item.options = this.generateOption(item.collectedDatas, item);
              } else if (item.type === '1') {
                item.playerOptions = this.generatePlayOption(item);
              } else if (item.type === '2') {
                item.options = this.generateStationOption(item.collectedDatas, item);
              }
            })
            this.charts = res.data;
            console.log(this.charts);
          }).finally(() => this.dataLoading = false)
        }
      }).catch(e => console.log(e));
    },
    handleExperimentChange(index) {
      this.activeIndex = index;
      this.dataLoading = true;
      let currentRow = this.experimentList[index];
      this.charts = [];
      getSchemeData({schemeId: currentRow.schemeId, size: 100}).then(res => {
        res.data.forEach(item => {
          if (item.type === '0') {
            item.options = this.generateOption(item.collectedDatas, item);
          } else if (item.type === '1') {
            item.playerOptions = this.generatePlayOption(item);
          } else if (item.type === '2') {
            item.options = this.generateStationOption(item.collectedDatas, item);
          }
        })
        this.charts = res.data;
      }).finally(() => this.dataLoading = false)
    },
    generateOption(data, item) {
      let xData = [];
      let yData = [];
      if (!data) {
        return ;
      }
      data.reverse();
      data.forEach(item => {
        xData.push(new Date(item.createTime).toLocaleTimeString());
        yData.push(item.actualValue);
      })
      console.log(calcFc(yData) !== NaN)
      let number = calcFc(yData);
      if (number) {
        item.fc = number.toFixed(6)
      } else {
        item.fc = 0
      }
      return {
        grid: commonGrid,
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            dataView: { readOnly: false },
            magicType: { type: ['line'] },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          data: xData
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} V'
          }
        },
        series: [
          {
            data: yData,
            type: 'line',
            markPoint: {
              data: [
                { type: 'max', name: 'Max' },
                { type: 'min', name: 'Min' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            }
          }
        ]
      }
    },
    generatePlayOption(item) {
      return {
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: "video/mp4",//这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
          src: item.recordFile ? item.recordFile.videopath.replaceAll('E:\\soft\\ffmpeg-record\\', 'http://192.168.1.110:8088/') : ''//url地址
        }],
        // poster: "../../static/images/test.jpg", //你的封面地址
        // width: document.documentElement.clientWidth, //播放器宽度
        notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true  //全屏按钮
        }
      }
    },
    generateStationOption(data, item) {
      let xData = [];
      let temp = {
        data1: [],
        data2: [],
        data3: [],
        data4: [],
        data5: [],
        data6: [],
        data7: [],
        data8: [],
      }
      data.reverse();
      data.forEach(item => {
        xData.push(new Date(item.createTime).toLocaleTimeString());
        item.formula.split(",").forEach((subItem, index) => {
          temp['data' + (++index)].push(Number(subItem).toFixed(2));
        })
      })
      return {
        grid: commonGrid,
        legend: {
          data: ['1号', '2号', '3号', '4号', '5号', '6号', '7号', '8号']
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            dataView: { readOnly: false },
            magicType: { type: ['line'] },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          data: xData
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} N'
          }
        },
        series: [
          {
            name: '1号',
            data: temp.data1,
            type: 'line',
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: '均值' }]
            }
          },
          {
            name: '2号',
            data: temp.data2,
            type: 'line',
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: '均值' }]
            }
          },
          {
            name: '3号',
            data: temp.data3,
            type: 'line',
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: '均值' }]
            }
          },
          {
            name: '4号',
            data: temp.data4,
            type: 'line',
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: '均值' }]
            }
          },
          {
            name: '5号',
            data: temp.data5,
            type: 'line',
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: '均值' }]
            }
          },
          {
            name: '6号',
            data: temp.data6,
            type: 'line',
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: '均值' }]
            }
          },
          {
            name: '7号',
            data: temp.data7,
            type: 'line',
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: '均值' }]
            }
          },
          {
            name: '8号',
            data: temp.data8,
            type: 'line',
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: '均值' }]
            }
          },
        ]
      }
    },
    exportData(item) {
      if (item.type === '0' || item.type === '2') {
        this.$confirm('是否确认导出采集数据?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          // this.exportLoading = true;
          this.loading = this.$loading({
            lock: true,
            text: "导出中...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          return exportCollected_data({collectItemId: item.collectionItemId});
        }).then(response => {
          this.download(response.msg);
        }).catch(() => {}).finally(() => this.loading.close());
      } else {
        this.downloadFileWithPath(item.recordFile.videopath.replaceAll('E:\\soft\\ffmpeg-record\\', 'http://192.168.1.110:8088/'))
      }
    },
    downloadFileWithPath(path) {
      let x=new XMLHttpRequest();
      x.open("GET", path, true);
      x.responseType = 'blob';
      x.onload=function(e){download(x.response, "dlBinAjax.mp4", "video/mp4" ); }
      x.send();
    }
  },
  created() {
    this.getList();
  },
  mounted() {
    window.onresize = debounce(() => {
      // this.$refs['yingLi'].resize();
    })
  }
}
</script>

<style scoped  lang="scss">
.experiment_data {
  padding: 10px;
  background-color: #f6f6f6;
  height: calc(100vh - 84px);
  width: 100%;
  display: flex;
  //1366 - 200px
  min-width: 1166px;
  .left_container {
    width: 300px;
    margin-right: 10px;
    background-color: white;
    overflow: hidden;
    position: relative;
    .experiment_item {
      border-bottom: 1px solid #D3EAE2;
      color: #999999;
      font-size: 14px;
      font-weight: 600;
      padding: 14px 44px 14px 22px;
      position: relative;
      transition: all .9s;
      &:hover {
        background-color: rgba(249, 255, 253, 1);
        cursor: pointer;
      }
      .active_block {
        background-color: #0CB37C;
        width: 5px;
        position: absolute;
        height: 71px;
        left: 0;
        top: -1px;
      }
      .active_arrow {
        position: absolute;
        right: 10px;
        top: 30px;
        color: #0CB37C;
      }
      .experiment_info {
        display: flex;
        justify-content: space-between;
        span {
          line-height: 16px;
        }
      }
      .experiment_time {
        font-size: 12px;
        margin-top: 12px;
      }
    }
    .experiment_item__active {
      background-color: rgba(249, 255, 253, 1);
    }
    .pagination_container {
      right: 0;
      bottom: 10px;
      position: absolute;
    }
  }
  .right_container {
    flex: 1;
    //min-width: 1000px;
    overflow-x: hidden;
    overflow-y: auto;
    justify-content: space-between;
    align-items: flex-start;
    flex-wrap: wrap;
    .right_item {
      width: calc(50% - 5px);
      margin-bottom: 10px;
      overflow: hidden;
      height: 410px;
      display: inline-block;
      position: relative;
      &:last-child {
        margin-bottom: 0;
      }
      &:nth-child(2n) {
        margin-left: 10px !important;
      }
    }
  }
}
.charts_container {
  width: 100%;
  position: relative;
  max-height: calc(100% - 38px)
}
.white_bg {
  background-color: white;
}
</style>
<style>
.video-js .vjs-tech {
  height: calc(100% - 60px) !important;
}
</style>
